package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.audit.aliyun.GreenImageScan;
import com.heima.audit.aliyun.GreenTextScan3;
import com.heima.audit.tess4j.Tess4jClient;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.common.redis.CacheService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.service.*;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.TesseractException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author: wxw
 * @ClassName: WmNewsAuditServiceImpl
 * @JdkVersion: JDK1.8
 * @Version: 1.0.0
 * @Since: 2025/2/19 14:49
 * @Description:
 */
@Slf4j
@Service
public class WmNewsAuditServiceImpl implements WmNewsAuditService {


    @Autowired
    private GreenTextScan3 greenTextScan3;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmChannelService wmChannelService;

    @Autowired
    private WmUserService wmUserService;

    @Autowired
    private WmNewsService wmNewsService;

    @Autowired
    private Tess4jClient tess4jClient;


    /**
     * 自媒体文章的自动审核
     */
    @GlobalTransactional  // 分布式事务控制
    @Async("taskExecutor")
    @Override
    public void auditWmNews(WmNews wmNews, List<String> contentImageList) {

        // 模拟审核是个耗时的业务,假如耗时10秒 测试时使用  //try {
        //        //    TimeUnit.SECONDS.sleep(10);
        //        //} catch (InterruptedException e) {
        //        //    throw new RuntimeException(e);
        //        //}


        //1. 准备待审核的内容
        //1.1 准备文章中全部的文本（标题 标签 内容） + 图片中的文本
        String allText = prepareAllText(wmNews);

        //1.2 准备文章中全部的图片URL地址
        Set<String> allImageList = prepareAllImage(wmNews, contentImageList);

        // 准备图片中的文本
        String ocrText = doImageOcr(allImageList);

        allText = allText + ocrText;


        //2. 第一阶段的审核:审核文本-DFA审核
        boolean flag = dfaTestScan(allText,wmNews);
        if (!flag) {
            log.error("[文章自动审核]DFA文本审核异常,可能是文本违规或不确定");
            // 返回值是void时,return 表示流程中断
            return ;
        }


        //3. 第二阶段的审核:阿里云审核文本
        flag = aliyunTestScan(allText,wmNews);
        if (!flag) {
            log.error("[文章自动审核]阿里云文本审核异常,可能是文本违规或不确定");
            // 返回值是void时,return 表示流程中断
            return ;
        }


        //4. 第三阶段的审核:审核图片
        flag = aliyunImageScan(wmNews, allImageList);
        if (!flag) {
            log.error("[文章自动审核]阿里云图片审核异常,可能是图片违规或不确定");
            return ;
        }



        //5. 根据发布时间处理文章发布
        long currentTime = System.currentTimeMillis(); // 系统当前时间
        long publishTime = wmNews.getPublishTime().getTime(); // 文章发布时间
        //5.1 如果发布时间大于系统时间，则修改文章状态为8自动审核通过，流程结束
        if (publishTime > currentTime) {
            wmNews.setStatus(WmNews.Status.SUCCESS.getCode()); //自动审核通过 8
            wmNews.setReason("自动审核通过待发布");
            wmNewsService.updateById(wmNews);
            log.info("[文章自动审核]发表时间未到,文章状态修改为自动审核通过待发布");
            return;
        }
        //5.2 如果发布时间小于等于系统时间，则修改文章状态为9已发布，调用Feign接口创建或修改APP文章
        this.doArticlePulish(wmNews);
        log.info("[文章自动审核]发表时间已到,文章状态修改为已发布");

    }

    /**
     * OCR技术
     * 获取图片中的文本
     */
    private String doImageOcr(Set<String> allImageList) {
        StringBuffer ocrText = new StringBuffer();
        if (allImageList.size() > 0) {
            for (String imageUrl : allImageList) {
                byte[] bytes = fileStorageService.downLoadFile(imageUrl);

                //图片识别文字审核---begin-----
                //从byte[]转换为butteredImage
                ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                try {
                    BufferedImage imageFile = ImageIO.read(in);
                    //识别图片的文字
                    String result = tess4jClient.doOCR(imageFile);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } catch (TesseractException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return ocrText.toString();
    }

    @Autowired
    private WmSensitiveService wmSensitiveService;

    @Autowired
    private CacheService cacheService;

    /**
     * DFA算法-文本审核
     */
    private boolean dfaTestScan(String allText, WmNews wmNews) {
        boolean flag = true;

        //2.1 查询redis列表中的敏感词列表
        List<String> sensitiveWordList = cacheService.lRange(WemediaConstants.SENSITIVE_List_KEY, 0, -1);

        if (sensitiveWordList.isEmpty()) {
            //2.2 如果redis中没有敏感词列表，则查询表中的数据存入redis中

            //2.2 查询表中已有的敏感词列表
            List<WmSensitive> wmSensitiveList = wmSensitiveService.list(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
            sensitiveWordList = wmSensitiveList.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
            cacheService.lLeftPushAll(WemediaConstants.SENSITIVE_List_KEY, sensitiveWordList);
        }

        //2.3 初始化DFA词库
        SensitiveWordUtil.initMap(sensitiveWordList);

        //2.4 对文中敏感词进行检测
        Map<String, Integer> map = SensitiveWordUtil.matchWords(allText);

        //2.4 根据返回结果进行处理
        if (map.size() > 0) {
            wmNews.setStatus(WmNews.Status.FAIL.getCode()); // 审核失败 2
            wmNews.setReason("DFA文本审核结果违规");
            wmNewsService.updateById(wmNews);
            flag = false;
        }
        return flag;
    }

    /**
     * 准备全部待审核的文本
     */
    private String prepareAllText(WmNews wmNews) {
        // 并发的情况下 使用StringBuffer  线程安全
        StringBuffer allText = new StringBuffer();
        allText.append(wmNews.getTitle()); //文本1：标题
        allText.append(wmNews.getLabels()); //文本2：标签

        List<Map> mapList = JSON.parseArray(wmNews.getContent(), Map.class);
        for (Map<String,String> map : mapList) {
            String type = map.get("type");
            if ("text".equals(type)) {
                allText.append(map.get("value")); //文本3：内容
            }
        }
        return allText.toString();
    }


    /**
     * 准备文章中全部的图片URL地址  准备全部的图片地址
     */
    private  Set<String> prepareAllImage(WmNews wmNews, List<String> contentImageList) {
        // 图片来源1：封面图片URL地址列表
        String coverImageStr = wmNews.getImages();
        List<String> coverImageList = new ArrayList<>();
        if (StringUtils.isNotBlank(coverImageStr)) {
            String[] coverImageArr = coverImageStr.split(",");
            coverImageList = Arrays.asList(coverImageArr);
        }

        // 图片来源2：内容图片URL地址列表，就是参数中的contentImageList  因为图片会有重复，所以需要去重
        Set<String> allImageList = new HashSet<>();
        allImageList.addAll(coverImageList);
        allImageList.addAll(contentImageList);
        return allImageList;
    }


    /**
     * 阿里云审核文本
     */
    private boolean aliyunTestScan(String allText, WmNews wmNews) {
        boolean flag = true;
        try {
            Map<String,String> map = greenTextScan3.greenTextScanStrongVersion(allText);
            String suggestion = map.get("suggestion");
            if ("review".equals(suggestion)) {
                //2.1 如果审核结果是review，将文章状态更改为3待人工审核，后续审核中止
                wmNews.setStatus(WmNews.Status.ADMIN_AUTH.getCode()); //待人工审核
                wmNews.setReason("阿里云文本审核结果不确定，等待人工审核");
                wmNewsService.updateById(wmNews);
                flag = false;
                //return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "阿里云文本审核结果不确定，等待人工审核");
            } else if ("block".equals(suggestion)) {
                //2.2 如果审核结果是block，将文章状态更改为2审核失败，后续审核中止
                wmNews.setStatus(WmNews.Status.FAIL.getCode()); // 待审核失败
                wmNews.setReason("阿里云文本审核结果违规");
                wmNewsService.updateById(wmNews);
                flag = false;
                //return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "阿里云文本审核结果违规");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(AppHttpCodeEnum.ALIYUN_AUDIT_ERROR);
        }

        return flag;
    }


    /**
     * 阿里云审核图片
     */
    private boolean aliyunImageScan(WmNews wmNews, Set<String> allImageList) {
        boolean flag = true;
        if (allImageList.size() < 0) {
            // 下载地址字节数组
            List<byte[]> imageByteList = new ArrayList<>();
            for (String imageUrl : allImageList) {
                byte[] imageBytes = fileStorageService.downLoadFile(imageUrl);
                imageByteList.add(imageBytes);
            }

            try {
                //Map<String, String> map = greenImageScan.imageScan(imageByteList);
                Map<String, String> map = new HashMap<>();
                map.put("suggestion", "pass");
                String suggestion = map.get("suggestion");
                if ("review".equals(suggestion)) {
                    //3.1 如果审核结果是review，将文章状态更改为3待人工审核，后续审核中止
                    wmNews.setStatus(WmNews.Status.ADMIN_AUTH.getCode()); //待人工审核 3
                    wmNews.setReason("阿里云图片审核结果不确定，等待人工审核");
                    wmNewsService.updateById(wmNews);
                    flag = false;
                    //return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "阿里云图片审核结果不确定，等待人工审核");
                }else if ("block".equals(suggestion)) {
                    //3.2 如果审核结果是block，将文章状态更改为2审核失败，后续审核中止
                    wmNews.setStatus(WmNews.Status.FAIL.getCode()); // 待审核失败 2
                    wmNews.setReason("阿里云图片审核结果违规");
                    wmNewsService.updateById(wmNews);
                    flag = false;
                    //return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "阿里云图片审核结果违规");
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new CustomException(AppHttpCodeEnum.ALIYUN_AUDIT_ERROR);
            }
        }
        return flag;
    }


    /**
     * 文章发布
     */
    private void doArticlePulish(WmNews wmNews) {
        ResponseResult responseResult;
        //if (publishTime <= currentTime) {
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode()); //已发布 9
        wmNews.setReason("自动审核已通过已发布");
        wmNewsService.updateById(wmNews);
        //}

        // 准备feign参数dto
        ArticleDto articleDto = new ArticleDto();
        articleDto.setTitle(wmNews.getTitle()); // 文章标题
        articleDto.setId(wmNews.getArticleId()); // app文章id
        articleDto.setContent(wmNews.getContent()); // 文章内容
        articleDto.setLabels(wmNews.getLabels()); // 文章标签
        articleDto.setLayout(wmNews.getType()); // 文章布局
        articleDto.setPublishTime(wmNews.getPublishTime()); // 文章发布时间
        if (articleDto.getId() == null) {
            articleDto.setCreatedTime(new Date()); // 创建时间
        }
        // 处理频道信息设置
        WmChannel wmChannel = wmChannelService.getById(wmNews.getChannelId());
        if (wmChannel != null) {
            articleDto.setChannelId(wmChannel.getId()); // 频道Id
            articleDto.setChannelName(wmChannel.getName()); // 频道名称
        }
        WmUser wmUser = wmUserService.getById(wmNews.getUserId());
        if (wmUser != null) {
            articleDto.setAuthorId(wmUser.getApUserId().longValue()); // 作者Id
            articleDto.setAuthorName(wmUser.getName()); // 作者名称
        }

        // 故意造异常  feign没调之前只能回滚本地
        //int i = 1 / 0;

        // 调用feign接口得到响应值
        responseResult = articleClient.saveOrUpdateArticle(articleDto);
        Integer code = responseResult.getCode();
        if (code != 200) {
            throw new CustomException(AppHttpCodeEnum.AP_ARTICLE_INVOKE_FAIL);
        }


        // 加载feign调用之后 相当于前面(文章详情页 文章创建 自媒体文章审核)全没做
        //int i = 1 / 0;


        // 从响应结果中取出app文章id
        Long articleId = Long.valueOf(String.valueOf(responseResult.getData()));
        wmNews.setArticleId(articleId);
        wmNewsService.updateById(wmNews);
    }

}
